package com.meihuayishu.backend.controller;

import com.meihuayishu.backend.common.ApiResponse;
import com.meihuayishu.backend.dto.*;
import com.meihuayishu.backend.service.UserService;
import com.meihuayishu.backend.service.DivinationRecordService;
import com.meihuayishu.backend.util.JwtUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/user")
@RequiredArgsConstructor
@Slf4j
@Tag(name = "用户数据服务", description = "用户信息管理、占卜记录、收藏功能")
public class UserDataController {
    
    private final UserService userService;
    private final DivinationRecordService divinationRecordService;
    private final JwtUtil jwtUtil;
    
    @GetMapping("/profile")
    @Operation(summary = "获取用户信息", description = "获取当前用户的详细信息")
    @Parameter(name = "Authorization", description = "Bearer Token", required = true)
    public ApiResponse<UserProfileResponse> getProfile(@RequestHeader("Authorization") String authorization) {
        try {
            log.info("获取用户信息请求");
            
            // TODO: 从JWT token中解析用户ID
            // String userId = extractUserIdFromToken(authorization);
            
            // 模拟响应数据
            UserProfileResponse.LocationInfo location = UserProfileResponse.LocationInfo.builder()
                    .province("广东省")
                    .city("深圳市")
                    .build();
            
            UserProfileResponse.StatisticsInfo statistics = UserProfileResponse.StatisticsInfo.builder()
                    .totalDivinations(28)
                    .favoriteCount(15)
                    .totalInterpretations(25)
                    .accuracyRating(4.2)
                    .registrationDays(90)
                    .build();
            
            UserProfileResponse.PreferencesInfo preferences = UserProfileResponse.PreferencesInfo.builder()
                    .defaultAlgorithm("TRADITIONAL")
                    .aiModel("WENXIN")
                    .interpretationLevel("PROFESSIONAL")
                    .notificationEnabled(true)
                    .privacyLevel("NORMAL")
                    .build();
            
            UserProfileResponse response = UserProfileResponse.builder()
                    .userId("user_1704096000123")
                    .phone("138****8000")
                    .nickname("易学爱好者")
                    .avatar("https://cdn.example.com/avatars/user123.jpg")
                    .realName("张**")
                    .gender("MALE")
                    .birthday(LocalDate.of(1995, 6, 15))
                    .location(location)
                    .level("进阶者")
                    .experience(1250)
                    .nextLevelExperience(2000)
                    .membershipType("VIP")
                    .membershipExpiry(LocalDateTime.of(2024, 12, 31, 23, 59, 59))
                    .statistics(statistics)
                    .preferences(preferences)
                    .createdAt(LocalDateTime.of(2023, 10, 1, 8, 0, 0))
                    .lastLoginAt(LocalDateTime.of(2024, 1, 1, 9, 30, 0))
                    .build();
            
            return ApiResponse.success(response, "获取成功");
        } catch (Exception e) {
            log.error("获取用户信息失败", e);
            return ApiResponse.error(500, "获取用户信息失败");
        }
    }
    
    @PutMapping("/profile")
    @Operation(summary = "更新用户信息", description = "更新用户个人信息")
    @Parameter(name = "Authorization", description = "Bearer Token", required = true)
    public ApiResponse<Map<String, Object>> updateProfile(
            @RequestHeader("Authorization") String authorization,
            @Valid @RequestBody UserProfileUpdateRequest request) {
        try {
            log.info("更新用户信息请求");
            
            // TODO: 实现用户信息更新逻辑
            // 1. 从JWT token中解析用户ID
            // 2. 验证用户权限
            // 3. 更新用户信息
            // 4. 记录操作日志
            
            Map<String, Object> response = Map.of(
                    "userId", "user_1704096000123",
                    "nickname", request.getNickname() != null ? request.getNickname() : "易学爱好者",
                    "avatar", request.getAvatar() != null ? request.getAvatar() : "",
                    "updatedFields", List.of("nickname", "avatar", "preferences"),
                    "updatedAt", LocalDateTime.now()
            );
            
            return ApiResponse.success(response, "更新成功");
        } catch (Exception e) {
            log.error("更新用户信息失败", e);
            return ApiResponse.error(400, e.getMessage());
        }
    }
    
    // ========== 占卜记录管理接口 ==========
    
    @PostMapping("/divination-records")
    @Operation(summary = "保存占卜记录", description = "保存占卜结果到用户历史记录")
    @Parameter(name = "Authorization", description = "Bearer Token", required = true)
    public ApiResponse<SaveDivinationRecordResponse> saveDivinationRecord(
            @RequestHeader("Authorization") String authorization,
            @Valid @RequestBody SaveDivinationRecordRequest request) {
        try {
            String userId = extractUserIdFromToken(authorization);
            log.info("保存占卜记录请求，用户ID: {}, 问题: {}", userId, request.getQuestion());
            
            SaveDivinationRecordResponse response = divinationRecordService.saveDivinationRecord(userId, request);
            return ApiResponse.success(response, "保存成功");
        } catch (Exception e) {
            log.error("保存占卜记录失败", e);
            return ApiResponse.error(500, "保存占卜记录失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/divination-records")
    @Operation(summary = "获取占卜历史记录", description = "分页获取用户占卜历史记录")
    @Parameter(name = "Authorization", description = "Bearer Token", required = true)
    public ApiResponse<DivinationHistoryResponse> getDivinationHistory(
            @RequestHeader("Authorization") String authorization,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer size,
            @RequestParam(defaultValue = "ALL") String type,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate,
            @RequestParam(defaultValue = "createdAt,desc") String sort) {
        try {
            String userId = extractUserIdFromToken(authorization);
            log.info("获取占卜历史记录请求，用户ID: {}, 页码: {}, 类型: {}", userId, page, type);
            
            DivinationHistoryResponse response = divinationRecordService.getDivinationHistory(
                    userId, page, size, type, startDate, endDate, sort);
            return ApiResponse.success(response, "获取成功");
        } catch (Exception e) {
            log.error("获取占卜历史记录失败", e);
            return ApiResponse.error(500, "获取占卜历史记录失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/divination-records/{recordId}")
    @Operation(summary = "获取占卜记录详情", description = "获取单个占卜记录的完整信息")
    @Parameter(name = "Authorization", description = "Bearer Token", required = true)
    public ApiResponse<DivinationRecordDetailResponse> getDivinationRecordDetail(
            @RequestHeader("Authorization") String authorization,
            @PathVariable String recordId) {
        try {
            String userId = extractUserIdFromToken(authorization);
            log.info("获取占卜记录详情请求，用户ID: {}, 记录ID: {}", userId, recordId);
            
            DivinationRecordDetailResponse response = divinationRecordService.getDivinationRecordDetail(userId, recordId);
            return ApiResponse.success(response, "获取成功");
        } catch (Exception e) {
            log.error("获取占卜记录详情失败", e);
            return ApiResponse.error(500, "获取占卜记录详情失败: " + e.getMessage());
        }
    }
    
    @DeleteMapping("/divination-records/{recordId}")
    @Operation(summary = "删除占卜记录", description = "删除指定的占卜记录")
    @Parameter(name = "Authorization", description = "Bearer Token", required = true)
    public ApiResponse<Map<String, Object>> deleteDivinationRecord(
            @RequestHeader("Authorization") String authorization,
            @PathVariable String recordId) {
        try {
            String userId = extractUserIdFromToken(authorization);
            log.info("删除占卜记录请求，用户ID: {}, 记录ID: {}", userId, recordId);
            
            boolean deleted = divinationRecordService.deleteDivinationRecord(userId, recordId);
            if (deleted) {
                return ApiResponse.success(Map.of("deleted", true, "recordId", recordId), "删除成功");
            } else {
                return ApiResponse.error(404, "记录不存在或删除失败");
            }
        } catch (Exception e) {
            log.error("删除占卜记录失败", e);
            return ApiResponse.error(500, "删除占卜记录失败: " + e.getMessage());
        }
    }
    
    // ========== 收藏功能接口 ==========
    
    @PostMapping("/favorites")
    @Operation(summary = "添加/取消收藏", description = "收藏或取消收藏占卜记录")
    @Parameter(name = "Authorization", description = "Bearer Token", required = true)
    public ApiResponse<FavoriteOperationResponse> toggleFavorite(
            @RequestHeader("Authorization") String authorization,
            @Valid @RequestBody FavoriteRequest request) {
        try {
            String userId = extractUserIdFromToken(authorization);
            log.info("收藏操作请求，用户ID: {}, 记录ID: {}, 操作: {}", userId, request.getRecordId(), request.getAction());
            
            FavoriteOperationResponse response = divinationRecordService.toggleFavorite(userId, request);
            String message = "ADD".equals(request.getAction()) ? "收藏成功" : "取消收藏成功";
            return ApiResponse.success(response, message);
        } catch (Exception e) {
            log.error("收藏操作失败", e);
            return ApiResponse.error(500, "收藏操作失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/favorites")
    @Operation(summary = "获取收藏列表", description = "获取用户收藏的占卜记录")
    @Parameter(name = "Authorization", description = "Bearer Token", required = true)
    public ApiResponse<FavoriteListResponse> getFavoriteList(
            @RequestHeader("Authorization") String authorization,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "20") Integer size) {
        try {
            String userId = extractUserIdFromToken(authorization);
            log.info("获取收藏列表请求，用户ID: {}, 页码: {}", userId, page);
            
            FavoriteListResponse response = divinationRecordService.getFavoriteList(userId, page, size);
            return ApiResponse.success(response, "获取成功");
        } catch (Exception e) {
            log.error("获取收藏列表失败", e);
            return ApiResponse.error(500, "获取收藏列表失败: " + e.getMessage());
        }
    }
    
    @PutMapping("/divination-records/{recordId}/tags")
    @Operation(summary = "更新记录标签", description = "更新占卜记录的标签")
    @Parameter(name = "Authorization", description = "Bearer Token", required = true)
    public ApiResponse<Map<String, Object>> updateRecordTags(
            @RequestHeader("Authorization") String authorization,
            @PathVariable String recordId,
            @RequestBody Map<String, List<String>> request) {
        try {
            String userId = extractUserIdFromToken(authorization);
            List<String> tags = request.get("tags");
            log.info("更新记录标签请求，用户ID: {}, 记录ID: {}, 标签: {}", userId, recordId, tags);
            
            boolean updated = divinationRecordService.updateRecordTags(userId, recordId, tags);
            if (updated) {
                return ApiResponse.success(Map.of("updated", true, "recordId", recordId, "tags", tags), "更新成功");
            } else {
                return ApiResponse.error(404, "记录不存在或更新失败");
            }
        } catch (Exception e) {
            log.error("更新记录标签失败", e);
            return ApiResponse.error(500, "更新记录标签失败: " + e.getMessage());
        }
    }
    
    // ========== 私有辅助方法 ==========
    
    private String extractUserIdFromToken(String authorization) {
        try {
            if (authorization != null && authorization.startsWith("Bearer ")) {
                String token = authorization.substring(7);
                return jwtUtil.getUserIdFromToken(token);
            }
            throw new RuntimeException("无效的认证令牌");
        } catch (Exception e) {
            log.error("解析用户ID失败", e);
            throw new RuntimeException("认证失败");
        }
    }
}